<?php
class XA_XHTML_Calendar extends XA_XHTML {
	
	public $year;
	public $month;
	public $caption;
	public $active;
	public $url_list = array();
	public $row_list = array();

	public function __construct($month, $year = null) {
		
		$this->month = $month;
		$this->year = ($year ? $year : date('Y'));
		$this->caption = XA_Date::$month_names[$this->month].' '.$this->year;
		
		$first = mktime(0, 0, 0, $this->month, 1, $this->year);
		$day_count = date('t', $first);
		$skip = (date('w', $first) + 6) % 7;
		
		$time = $first - $skip * 3600 * 24;
		$cell_count = ceil(($day_count + $skip) / 7) * 7;
		$day_list = array();
		while ($cell_count) {
			$day = array();
			if (date('n', $time) != $this->month) {
				$day['class'] = 'other';
			} else {
				$day['class'] = '';
				$day['current_month'] = true;
			}
			if ($time == mktime(0, 0, 0)) {
				$day['class'] .= ' today';
			}
			$day['content'] = date('j', $time);
			$day['weekday'] = (date('w', $time) + 6) % 7;
			if ($day['weekday'] == 6) {
				$day['class'] .= ' sun';
			}
			if ($day['weekday'] == 5) {
				$day['class'] .= ' sat';
			}
			$day['week'] = date('W', $time);
			$day_list[] = $day;
			$time += 3600 * 24;
			$cell_count--;
		}
		
		foreach ($day_list as $day) {
			$this->row_list[$day['week']][$day['weekday']] = $day;
		}
		
		$this->classes[] = 'calendar';
	}
	
	public function getOutput() {
		
		if (empty($this->active)) {
			$this->active = date('j');
		}
		
		$rows = '';
		foreach ($this->row_list as $row) {
			$rows .= '<tr>';
			foreach ($row as $cell) {
				if (($cell['content'] == $this->active) && !empty($cell['current_month'])) {
					$cell['class'] .= ' active';
				}
				$rows .= '<td'.(!empty($cell['class']) ? ' class="'.$cell['class'].'"' : '').'>';
				if (!empty($this->url_list[$cell['content']]) && !empty($cell['current_month'])) {
					$rows .= '<a href="'.$this->url_list[$cell['content']].'">'.$cell['content'].'</a>';
				} else {
					$rows .= $cell['content'];
				}
				$rows .= '</td>';
			}
			$rows .= '</tr>';
		}
		
		return '
			<table'.($this->classes?' class="'.implode(' ', $this->classes).'"':'').'>
				<caption>'.$this->caption.'</caption>
				<thead>
					<tr>
						<th>Pn</th>
						<th>Wt</th>
						<th>Śr</th>
						<th>Cz</th>
						<th>Pt</th>
						<th>Sb</th>
						<th>Nd</th>
					<tr>
				</thead>
					
				<tbody>
					'.$rows.'
				</tbody>
				
			</table>
			';
	}
}
